package com.example.ssmlab2.controller;

import com.example.ssmlab2.model.Book;
import com.example.ssmlab2.model.User;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;
import java.util.function.Consumer;

/**
 * ClassName:UserController
 * Package:com.example.ssmlab2.controller
 * Description:
 *
 * @Author:ZhangXin
 * @Create:2023/4/1-13:32
 * @Version:v1.0
 */
@Controller
@RequestMapping("user")
public class UserController extends BaseController {

    private SqlSession sqlSession;

    public UserController(SqlSession sqlSession) {
        this.sqlSession = sqlSession;
    }

    //登录界面控制
    @RequestMapping(value = "signIn", method = RequestMethod.POST)
    public String signIn(User user) {
        user = sqlSession.selectOne("user.queryUserByUsernameAndPassword", user);

        if (user == null) {
            request.setAttribute("error", "用户名或密码错误");
            return "/index.jsp";
        } else if (user.getUsername().equals("admin")) {
            List<Book> book = sqlSession.selectList("user.queryAllBooks",new Book());
            session.setAttribute("book",book);
            return "redirect:/admin/bookManagement.jsp";
        } else {
            List<Book> book = sqlSession.selectList("user.queryAllBooks",new Book());
            session.setAttribute("book",book);
            return "redirect:/book.jsp";
        }
    }

    //注册界面
    @RequestMapping(value = "signUp", method = RequestMethod.POST)
    private String signUp(User user) {
        sqlSession.insert("user.create", user);
        session.setAttribute("id", "您的id是" + user.getId());
        return "redirect:/index.jsp";
    }

    //退出
    @RequestMapping(value = "signOut",method = RequestMethod.GET)
    private String signOut(){
        session.invalidate();
        return "redirect:/index.jsp";
    }


}
